<?php

    $content = '';
    if ($_SESSION['logged']) {
        include('data/lib_components.inc.php');
        include('data/lib_f_admin.inc.php');
    }
    $groups = array('error','club','Polo','Surf','Whitewater','Social','Combos','Committee');
    /**
    * Send new Newsletter
    */
    if ($_POST['submitted']) {
        include('data/lib_f_validate.inc.php');
        extract($_POST);
        
        if (!$Title = validateText($Title)) $err .= 'Title invalid.<br>';
        if (!$Text = validateText($Text,true)) $err .= 'Text invalid.<br>';
        
        if (!$err) {
            if ($NID = mq("INSERT INTO newsletter (MID,Title,Text,Date,`group`) VALUES (".$_SESSION['MID'].",'$Title','$Text',NOW(),$group)")) {
              include('data/class.phpmailer.php');
              $content .= 'Composing mails..<br>';
              $mail = new PHPMailer();
              $mail->IsMail();
      
              $mail->From     = mqs("SELECT eMail FROM members WHERE MID=".$_SESSION['MID']);
              $mail->FromName = $_SESSION['username'];
              
              $mail->WordWrap = 50;
              $mail->IsHTML(true);
              $GNID = mqs("SELECT COUNT(*) FROM `newsletter` WHERE `group`=".$group) + 1;
              $subject = "UCCC-".$groups[$group]." email #".$GNID.': '.$Title;
              $mail->Subject  =  $subject;
              $mail->Body     =  '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
                    <html>
                      <head>
                        <meta http-equiv="content-type" content="text/html;CHARSET=iso-8859-1">
                      </head>
                      <body style="background-color:#CCCCFF; color: #336699; font: 12pt Verdana, Arial; margin: 20px">
                      <b>'.$subject.'</b><br>
                      <br>'
                      .$Text
                      .'</body>
                    </html>';  
             
              $addispermail = 15;  $err = '';
              $query = "SELECT Name,eMail FROM members WHERE send_news=1";
              /* Groups: 1 is whole club, 2 is polo, 3 is surf, 4 is river, 5 is social, 6 is combos, 7 is committee */
              if($group==2){ $query .= ' AND news_polo=1';}
              elseif($group==3){ $query .= ' AND news_surf=1';}
              elseif($group==4){ $query .= ' AND news_river=1';}
              elseif($group==5){ $query .= ' AND news_social=1';}
              elseif($group==6){ $query .= ' AND news_combos=1';}
              elseif($group==7){ $query .= ' AND Rights & ' . $r_comittee;}
              $cnt = 0; $it = 1; $success = true;
              if ($qres = mq($query)) 
              {
                  $content .= '<br>Sending to ' . mysql_numrows($qres) .' people...<br>';
                while($member = mysql_fetch_row($qres)) {
                    $mail->AddBCC($member[1],$member[0]); 
                    $cnt++;
                    if ($cnt % $addispermail == 0) {
                       $res = $mail->Send();
                       if (!$res) {
                            $err .= 'Error in iteration '.$it.': '.$mail->ErrorInfo.'<br>\n';
                            $success = false;
                            break;
                       }
                       $mail->ClearBCCs();
                       $cnt = 0;
                       $content .= 'Sent mails: '.($it-1)*$addispermail.' - '.$it*$addispermail.'<br>';
                       $it++;
                    }
                }
              }  #*/
              if ($success && $cnt > 1) 
              {
                  $res = $mail -> Send();
                  if (!$res) {
                            $err .= 'Error in iteration '.$it.': '.$mail->ErrorInfo.'<br>\n';
                            $success = false;
                  } else {
                      $content .= 'Sent mail '.($it-1)*$addispermail.' - '.(($it-1)*$addispermail+$cnt).' <br><br><hr />';
                  }
              }
              #if (false) {
              if ($success) {
                  logevent("Newsletter #".$NID." sent to ".$groups[$group]);
              } else  { 
                  mq("DELETE FROM newsletter WHERE NID=".$NID);
                  mq("ALTER TABLE newsletter AUTO_INCREMENT=".$NID);
                  logevent('Error sending Newsletter #'.$NID.':<br>'.$err);
                  $content .= $err;
              }
            }
        }
    }
  
  /**
  *  Display an old newsletter
  *  Groups: 1 is whole club, 2 is polo, 3 is surf, 4 is river, 5 is social, 6 is combos, 7 is committee
  */
  if ($_GET['NID']) {
                                                                                          
     if ($entry = mqs("SELECT Date,Title,Text,`group`,Name FROM newsletter n
                   INNER JOIN members m ON m.MID=n.MID
                   WHERE NID=".($_GET['NID']+0))) 
     {
         extract($entry);   
         $groups = array('error','everyone in the Club','everyone signed up to recieve messages about Polo','everyone signed up to recieve messages about Surf','everyone signed up to recieve messages about Whitewater','everyone signed up to recieve messages about Social','everyone signed up to recieve messages about combos','the committee');
         $group = $groups[$group];
     $content .= '<a href="'.$_SERVER['PHP_SELF'].'" title="Back to overview">Back to overview</a>';
     $content .= '<table style="width:100%" cellpadding="3">
                     <tr><td><b>Sent to: </b></td><td style="text-align:right">'.$group.'</td></tr>
                     <tr><td><b>'.$Title.'</b></td><td style="text-align:right">'.formatDate($Date).'</td></tr>
                     <tr><td colspan="2" style="text-align:right">'.$Name.'</td></tr>
                     <tr><td colspan="2">'.$Text.'</td></tr>
                 </table>';
     }
  
  /**
  *  Write a new Letter
  */
  } else if (($err || $_GET['newletter']) && $_SESSION['logged']) {# && ($_SESSION['rights'] & ($r_comittee | $r_webmaster))) {
    $content .= 'Here you can send an email to select groups:<br>
                 '.($err ? '<font color="red">'.$err.'</font><br>':'').'
                 <form action="'.$_SERVER['PHP_SELF'].'" method="POST">
                 <table style="width:100%" cellpadding="3">
                     <tr><td>Mail the whole Club ('.mqs("SELECT COUNT(*) FROM `members` WHERE send_news=1").')</td><td> <input name="group" type="radio" id="group" value="1" checked="checked" /></td></tr>
                     <tr><td>subscribed to Polo messages ('.mqs("SELECT COUNT(*) FROM `members` WHERE send_news=1 AND news_polo=1").')</td><td> <input name="group" type="radio" id="group" value="2" /></td></tr>
                     <tr><td>subscribed to Surf messages ('.mqs("SELECT COUNT(*) FROM `members` WHERE send_news=1 AND news_surf=1").')</td><td> <input name="group" type="radio" id="group" value="3" /></td></tr>
                     <tr><td>subscribed to Whitewater messages ('.mqs("SELECT COUNT(*) FROM `members` WHERE send_news=1 AND news_river=1").')</td><td> <input name="group" type="radio" id="group" value="4" /></td></tr>
                     <tr><td>subscribed to Social messages ('.mqs("SELECT COUNT(*) FROM `members` WHERE send_news=1 AND news_social=1").')</td><td> <input name="group" type="radio" id="group" value="5" /></td></tr>
                     <tr><td>subscribed to Combos messages ('.mqs("SELECT COUNT(*) FROM `members` WHERE send_news=1 AND news_combos=1").')</td><td> <input name="group" type="radio" id="group" value="6" /></td></tr>
                     <tr><td>the UCCC Committee ('.mqs("SELECT COUNT(*) FROM `members` WHERE send_news=1 AND Rights&". $r_comittee) .')</td><td> <input name="group" type="radio" id="group" value="7" /></td></tr>
                     <tr><td><hr /><br />Title: <input type="text" name="Title" value="'.$Title.'" maxlength="100" class="text" size="40"></td>
                     <td style="text-align:right">'.formatDate(date("Y-m-d")).'</td></tr>
                     <tr><td colspan="2" style="text-align:right">'.$_SESSION['username'].'</td></tr>
                     <tr><td colspan="2">Your text:<br><textarea name="Text" cols="60" rows="16">'.$Text.'</textarea></td></tr>
                     <tr><td colspan="2" style="text-align:center">
                       <input type="submit" class="button" onclick="return confirm(\'Really send Newsletter?\nThis will go out to all members signed up for this newsletter!\')" value="Send Newsletter!">
                       </td></tr>
                 </table>
                 <input type="hidden" name="submitted" value="1">
                 </form>';
  
  
  /**
  * Display list of letters
  */
  } else {
     if ($_SESSION['logged']) {
        $content .= '<a href="'.$_SERVER['PHP_SELF'].'?newletter=1">Write new newsletter</a><br>';
     }
     if ($res = mq("SELECT NID,Date,Title,Name,m.MID FROM newsletter n
                    INNER JOIN members m ON m.MID=n.MID
                    ORDER BY Date DESC,Name")) {
         $content .= '<table cellpadding="3" style="width:100%"><tr>
                       <th>Date</th><th>Title</th><th>From</th></tr>';
         
         while($data = mysql_fetch_array($res)) {
            $content .= '<tr>
                           <td style="width:80px">'.formatDate($data['Date']).'</td>
                           <td><a href="'.$_SERVER['PHP_SELF'].'?NID='.$data['NID'].'" title="'.$data['Title'].'">'.$data['Title'].'</a></td>
                           <td style="width:100px">'.$data['Name'].'</td>
                         </tr>';
         }
         $content .= '</table>';               
     } else $content .= "no newsletters yet.";
  } 
  
?>